<script setup lang="ts">
import type { TabBar } from "@/typings/comps/comps";
import { getCurrentInstance } from "vue";
import { useGlobalStore } from "@/stores/modules/global";
import { useGetNodeElement } from "@/utils";

/**
 * @description {Component} 自定义底部导航栏
 * @prop {string | number} v-model:modelValue 当前选中的 tabBar index
 * @prop {boolean} customizeTabBarEnable 是否使用自定义 tabBar
 * @prop {Array<TabBar.tabBarListItem>} tabBarList tabBar 列表
 * @prop {string} keyName 指定value 的 key 的名称
 * @author 花东红
 * @time 2025/7/29
 */
const props = withDefaults(defineProps<TabBar.Props>(), {
  modelValue: 0,
  customizeTabBarEnable: false,
  tabBarList: () => [],
  keyName: ""
});

const emit = defineEmits(["change", "update:modelValue"]);

const globalStore = useGlobalStore();

const { proxy } = getCurrentInstance() as any;

const tabBarHeight = computed(() => globalStore.initialState.tabBarHeight);

const handleTabBarChange = (item: useGlobalStoreType.tabBarListItem, index: number) => {
  // @ts-expect-error keyName
  if (props.modelValue === (props.keyName ? item[props.keyName] : index)) return;
  // @ts-expect-error keyName
  emit("update:modelValue", props.keyName ? item[props.keyName] : index);
  emit("change", { item, index });
};

const getNodeElement = async () => {
  const node = await useGetNodeElement(proxy, ".tabBarContainer");
  globalStore.setGlobalState({ key: "tabBarHeight", value: node.height ?? 0 });
};

onMounted(() => {
  getNodeElement();
});
</script>

<template>
  <view :style="{ height: `${tabBarHeight}px` }" v-if="props.customizeTabBarEnable">
    <view class="tabBarContainer">
      <wd-tabbar-item v-for="(item, index) in props.tabBarList" :key="item.name" :value="item.value" :is-dot="item.isDot" @tap="handleTabBarChange(item, index)">
        <template #icon>
          <view class="flex flex-col justify-center items-center">
            <image :src="props.modelValue === (props.keyName ? item[props.keyName] : index) ? item.selectedIconPath : item.iconPath" class="w-[48rpx] h-[48rpx]" />
            <view class="mt-[4rpx]" :style="{ color: props.modelValue === (props.keyName ? item[props.keyName] : index) ? item.activeColor : item.inactiveColor, fontSize: `${item.fontSize}rpx` }">{{ item.name }}</view>
          </view>
        </template>
      </wd-tabbar-item>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.tabBarContainer {
  @apply w-full fixed z-[99] bottom-[0] border-solid border-t-[#FFFFFF] border-t-[1rpx] flex justify-between items-center bg-[var(--wot-color-theme)] pt-[8rpx] pb-[constant(safe-area-inset-bottom)] pb-[env(safe-area-inset-bottom)];
}
</style>
